/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.casemain.service.impl;

import com.icinfo.cloud.provider.common.enums.RecordSaveTypeEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CasePartiesPersonInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CasePartiesRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CasePartiesPersonInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CasePartiesRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesPersonInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesPersonInfoVo;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 描述: 案件当事人个人详细信息-TRJ case_parties_person_info 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月15日
 */
@Service
@Slf4j
public class CasePartiesPersonInfoServiceImpl extends MyBatisServiceSupport implements ICasePartiesPersonInfoService {
    @Resource
    private CasePartiesPersonInfoMapper casePartiesPersonInfoMapper;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;

    /**
     * 【V1.0.0】描述：保存案件当事人-个人信息
     *
     * @param saveDto {@link CasePartiesPersonInfoDto}
     * @return int 保存成功记录数
     * @author xiangyuyu
     * @date 2022-02-18 16:02
     */
    @Override
    public int saveCasePartiesPersonInfo(CasePartiesPersonInfoDto saveDto) {
        //判断新增还是修改
        String operateType = saveDto.getOperateType();
        if(!RecordSaveTypeEnum.isLegalEnumCode(operateType)){
            throw new BusinessException("请指定有效的操作类型(1-新增/2-修改)");
        }
        String errorMsg = validatePersonInfo(saveDto);
        if (!ObjectUtils.isEmpty(errorMsg)) {
            throw new BusinessException(errorMsg);
        }
        CasePartiesPersonInfo personInfo = new CasePartiesPersonInfo();
        BeanUtils.copyProperties(saveDto, personInfo);
        personInfo.setBirth(BaseUtil.getFormatDate(saveDto.getBirth()));
        //增加年龄处理
        personInfo.setAge(BaseUtil.getAgeByBirth(saveDto.getBirth()));
        if (ObjectUtils.isEmpty(personInfo.getId())) {
            personInfo.setId(BaseUtil.createUid());
        }
        int count;
        String caseId = saveDto.getCaseId();
        String partyId = saveDto.getId();
        if(RecordSaveTypeEnum.ADD.getCode().equals(operateType)){
            count = casePartiesPersonInfoMapper.insertSelective(personInfo);
        } else {
            //校验caseId+partyId是否匹配，匹配后才允许修改
            CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto();
            queryDto.setCaseId(caseId);
            queryDto.setPartyId(partyId);
            queryDto.setIsQueryInvalidData(saveDto.getIsQueryInvalidData());
            List<CasePartiesInfoVo> list = casePartiesRecordService.getCasePartiesInfoList(queryDto);
            if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                //允许修改
                count = casePartiesPersonInfoMapper.updateByPrimaryKeySelective(personInfo);
            } else {
                throw new BusinessException("案件id和当事人id不匹配，无法进行更新");
            }
        }
        return count;
    }

    /**
     * 描述：校验个人信息
     *
     * @param dto {@link CasePartiesPersonInfoDto}
     * @return String 错误信息
     * @author xiangyuyu
     * @date 2022-06-20 11:46
     */
    private String validatePersonInfo(CasePartiesPersonInfoDto dto) {
        if (ObjectUtils.isEmpty(dto.getAddressAreas())) {
            return "住址-省市区不能为空（逗号分隔）";
        }
        if (ObjectUtils.isEmpty(dto.getAddressDetail())) {
            return "住址-详细地址不能为空";
        }
        if (ObjectUtils.isEmpty(dto.getName())) {
            return "当事人姓名不能为空";
        }

        if (ObjectUtils.isEmpty(dto.getName())) {
            return "当事人姓名不能为空";
        }
        if (ObjectUtils.isEmpty(dto.getSex())) {
            return "当事人性别不能为空";
        }
        if (ObjectUtils.isEmpty(dto.getBirth())) {
            return "当事人出生年月不能为空";
        }
//        if (ObjectUtils.isEmpty(dto.getMobile())) {
//            return "当事人联系电话不能为空";
//        }
        if (ObjectUtils.isEmpty(dto.getCertType())) {
            return "当事人证件类型不能为空";
        }
        if (ObjectUtils.isEmpty(dto.getCertNo())) {
            return "当事人证件号码不能为空";
        }
        if (ObjectUtils.isEmpty(dto.getAddress())) {
            return "当事人住址不能为空";
        }
        //当事人工作单位校验去掉，非必填
//        if (ObjectUtils.isEmpty(dto.getUnitName())) {
//            return "当事人工作单位不能为空";
//        }
        return null;
    }

    /**
     * 【V1.0.0】描述：获取案件当事人-个人信息分页列表
     *
     * @param pageRequest {@link CasePartiesPersonInfoPageRequest}
     * @return {@link Result< List < CasePartiesPersonInfoVo >>} 案件当事人-个人信息分页列表
     * @author xiangyuyu
     * @date 2022-02-18 16:02
     */
    @Override
    public List<CasePartiesPersonInfoVo> getCasePartiesPersonInfoPageList(CasePartiesPersonInfoPageRequest pageRequest) {
        return null;
    }

    /**
     * 【V1.0.0】描述：获取案件当事人-个人信息列表
     *
     * @param queryDto {@link CasePartiesPersonInfoQueryDto}
     * @return {@link List<CasePartiesPersonInfoVo>} 案件当事人-个人信息列表
     * @author xiangyuyu
     * @date 2022-02-18 16:02
     */
    @Override
    public List<CasePartiesPersonInfoVo> getCasePartiesPersonInfoList(CasePartiesPersonInfoQueryDto queryDto) {
        return null;
    }

    /**
     * 【V1.0.0】描述：根据唯一标识查询案件当事人-个人信息
     *
     * @param id 唯一标识
     * @return {@link CasePartiesPersonInfoVo} 案件当事人-个人信息
     * @author xiangyuyu
     * @date 2022-02-18 16:02
     */
    @Override
    public CasePartiesPersonInfoVo getCasePartiesPersonInfo(String id) {
        log.info("getCasePartiesPersonInfo start(id:+" + id + ")...");
        CasePartiesPersonInfo casePartiesPersonInfo = casePartiesPersonInfoMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(casePartiesPersonInfo)) {
            throw new BusinessException("未找到个人信息");
        }
        CasePartiesPersonInfoVo vo = new CasePartiesPersonInfoVo();
        BeanUtils.copyProperties(casePartiesPersonInfo, vo);
        log.info("getCasePartiesPersonInfo end-vo:" + vo);
        return vo;
    }

    /**
     * 【V1.0.0】描述：删除案件当事人-个人信息
     *
     * @param id 主键id
     * @return {@link Result<String>} 删除结果
     * @author xiangyuyu
     * @date 2022-02-18 16:02
     */
    @Override
    public Result<String> removeCasePartiesPersonInfo(String id) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveCasePartiesPersonInfoWithAdjust(CasePartyRecordAdjustPersonSaveDto saveDto) {
        //判断新增还是修改
        String operateType = saveDto.getOperateType();
        if(!RecordSaveTypeEnum.isLegalEnumCode(operateType)){
            throw new BusinessException("请指定有效的操作类型(1-新增/2-修改)");
        }
        CasePartiesPersonInfo personInfo = new CasePartiesPersonInfo();
        BeanUtils.copyProperties(saveDto, personInfo);
        personInfo.setAddressAreas( StringUtils.join(saveDto.getAddressAreas(),","));
        personInfo.setBirth(saveDto.getBirth());
        //增加年龄处理
        personInfo.setAge(BaseUtil.getAgeByBirth(saveDto.getBirth()));
        if (ObjectUtils.isEmpty(personInfo.getId())) {
            personInfo.setId(BaseUtil.createUid());
        }
        int count;
        String caseId = saveDto.getCaseId();
        String partyId = saveDto.getId();

        CasePartiesRecord casePartiesRecord = new CasePartiesRecord();
        BeanUtils.copyProperties(saveDto, casePartiesRecord);
        casePartiesRecord.setCaseId(caseId);
        casePartiesRecord.setAddressDetail(saveDto.getAddressDetail());
        casePartiesRecord.setPartyIdentityCode(saveDto.getCertNo());
        casePartiesRecord.setPartyIdentityType(saveDto.getCertType());
        casePartiesRecord.setPartyName(saveDto.getName());
        casePartiesRecord.setPartyType(PartyTypeEnum.PERSON.getCode());
        casePartiesRecord.setPartyId(partyId);
        casePartiesRecord.setId(BaseUtil.createUid());
        casePartiesRecord.setAddressAreas(personInfo.getAddressAreas());
        if(RecordSaveTypeEnum.ADD.getCode().equals(operateType)){
            count = casePartiesPersonInfoMapper.insertSelective(personInfo);
        } else {
            //校验caseId+partyId是否匹配，匹配后才允许修改
            CasePartiesRecordQueryDto queryDto = new CasePartiesRecordQueryDto();
            queryDto.setCaseId(caseId);
            queryDto.setPartyId(partyId);
            queryDto.setIsQueryInvalidData(saveDto.getIsQueryInvalidData());
            List<CasePartiesInfoVo> list = casePartiesRecordService.getCasePartiesInfoList(queryDto);
            if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                //允许修改
                count = casePartiesPersonInfoMapper.updateByPrimaryKeySelective(personInfo);
                //将修改前的无效掉
                casePartiesRecordService.delCasePartiesRecordByPartyId(partyId);
            } else {
                throw new BusinessException("案件id和当事人id不匹配，无法进行更新");
            }
        }
        //保存到文书记录表
        count = casePartiesRecordMapper.insertSelective(casePartiesRecord);
        return partyId;
    }

}
